<?php
namespace Wx\Controller;

use Think\Controller;
use Think\Model;

class SearchController extends BaseController
{

    public function _initialize()
    {

    }

    /**
     * 店内搜索历史记录
     */
    public function shopSearch(){
        $this->shop_id=I('shop_id');

        //回退到商店
        $this->ref = '/Wx/Shop/shop?id='.I('shop_id').'&ref=/Wx/Index/index';
        $this->shop_id = I('shop_id');
        $this->display('shop_search');
    }



    /**
     * 店内搜索商品
     */
    public function shopGoodsSearch(){
        $this->list = D('Search')->getShopGoods();

        $this->keyword = urldecode(I('key'));
        $this->shop_id = I('shop_id');

        if(session('oto_userId')){
            $this->isLogin = 1;
        }else{
            $this->isLogin = 0;
        }

        $this->display('diannei');
    }

    public function searchF(){
        $this->display('search');
    }

    //获取商品
    public function getGoods(){

        $m = D('Search');

        $goodsList = $m->keyGoods();
        if(!session('lon')){
            session('lat',I('lat'));
            session('lon',I('lon'));
            session(array('name'=>'lon','expire'=>86400));
            session(array('name'=>'lon','expire'=>86400));
        }

       if($goodsList){
            $list = [];
            $shopId = implode(',',array_keys($goodsList));
            $list = $m->getShop($shopId);
            //将商品信息放入店铺之中
            foreach($list as $k=>$v){
                if($goodsList[$v['shopId']]){
                    $list[$k]['goodsList']= $goodsList[$v['shopId']];
                }
            }
        }


        $this->ajaxReturn($list) ;
    }

    public function index(){

        $this->keyword=I('key');
        $this->load = 1;


        if(session('lon')){
            $this->load = 0;
            $this->lat = session('lat');
            $this->lon = session('lon');
        }


        $str = '';
        foreach($_GET as $k => $v){
            $str.= ('/'.$k.'/'.$v);
        }
        if($str) $this->shopRef = '&ref=/Wx/Search/index'.$str;
        if(I('type')=='shops'){
            $this->cate = $this->getCart();
            $this->display('search-shops');
            return;
        }else if(I('type')=='cate'){
            $this->cate = $this->getCart();
            $this->catId=I('lei');
            $this->title=M('goods_cats')->where(['catId'=>I('lei')])->getField('catName');
            $this->display('search-cate');
            return;
        }

        $this->display('search-goods');
    }

    //获取分类
    public function getCart(){
        //店铺分类
        $cat=M('goods_cats')->where(array('isShow'=>1,'catFlag'=>1))->order('catSort ASC')->select();
        $levelOne=[];
        foreach ($cat as $key=>$value){
            if($value['parentId']==0){
                $levelOne[]=$value;
            }
        }

        $res = $this->arrayPidProcess($cat);

        foreach($res as $k=>$v){
            if($v['child']){
                $res[$k]['info']['count'] = count($v['child']);
                foreach($v['child'] as $k1 => $v1){
                    $res[$k]['child'][$k1]['info']['count']= count($v1['child']);
                }
            }
        }
        return $res;
    }

     //递归分类
    function arrayPidProcess($data,$res=array(),$pid='0'){
        foreach ($data as $k => $v){
            if($v['parentId']==$pid&&$v['isShow']==1&&$v['catFlag']==1){
                $res[$v['catId']]['info']=$v;
                $res[$v['catId']]['child']=$this->arrayPidProcess($data,array(),$v['catId']);
            }
        }
        return $res;
     }



    public function search()
    {
        $brand = I('bid');
        $page = I('get.page');
        $sort = I('get.sorts');
        $type = I('get.type');
        $sales = I('get.sales');
        $star = I('get.star');
        $end = I('get.end');
        $key = I('get.key');
        $mtime = time();
        $limit = 10;
        $step = $page * $page;

        if (! is_numeric($star)) {
            $star = 0;
        }
        if (! is_numeric($end)) {
            $end = 0;
        }
        //搜索商品
        if ($type == 'goods' && ! empty($key)) {
            $order = "";
            $sale = "";
            if ($sales) {
                $sale = 'monthCount DESC , ';
            }
            switch ($sort) {
                // 智能
                case 'smart':
                    $order = "$sale goodsId DESC";
                    break;
                // 配送费
                case 'freight':
                    $order = "$sale deliveryStartMoney ASC";
                    break;
                // 销量
                case 'volume':
                    $order = "monthCount DESC";
                    break;
                default:
                    $order = "goodsId DESC";
            }
            $where = " where g.goodsName like '%$key%' ";
            if($brand){
                $where = " where g.goodsName like '%$key%' and g.brandId = $brand ";
            }

            $where.=" and goodsFlag=1 and goodsStatus=1";
            if ($star && $end) {
                if ($end > $star) {
                    $having = " HAVING  g.shopPrice between $star and $end ";
                } else {
                    $having = " HAVING   g.shopPrice >= $star ";
                }
            } else
                if ($star && ! $end) {
                    $having = " HAVING   g.shopPrice >= $star ";
                } else
                    if (! $star && $end) {
                        $having = "  HAVING  g.shopPrice <=$end ";
                    }

            $sql = <<<Eof
SELECT
	g.goodsId,
	g.goodsName,
	g.goodsThums,
	g.marketPrice,
	g.shopPrice,
	s.deliveryStartMoney,
	(
		SELECT
			count(goodsId)
		FROM
			oto_order_goods
		JOIN oto_orders ON oto_order_goods.orderId = oto_orders.orderId
		WHERE
			(
				oto_orders.isPay = 1
				OR oto_orders.payType = 0
			)
		AND oto_orders.isClosed = 0
		AND oto_orders.isRefund = 0
        AND oto_orders.paytime-$mtime<2592000
		AND oto_order_goods.goodsId = g.goodsId
	) AS monthCount
FROM
	oto_goods AS g
LEFT JOIN oto_order_goods AS og ON g.goodsId = og.goodsId
LEFT JOIN oto_shops AS s ON s.shopId = g.shopId
$where
GROUP BY
	og.goodsId
	$having
ORDER BY
	$order
limit $step,$limit
Eof;


            $csql = <<<Eof
SELECT
	g.goodsId,
	g.goodsName,
	g.goodsThums,
	g.marketPrice,
	g.shopPrice,
	s.deliveryStartMoney,
	(
		SELECT
			count(goodsId)
		FROM
			oto_order_goods
		JOIN oto_orders ON oto_order_goods.orderId = oto_orders.orderId
		WHERE
			(
				oto_orders.isPay = 1
				OR oto_orders.payType = 0
			)
		AND oto_orders.isClosed = 0
		AND oto_orders.isRefund = 0
		AND oto_orders.paytime-$mtime<2592000
		AND oto_order_goods.goodsId = g.goodsId
	) AS monthCount
FROM
	oto_goods AS g
LEFT JOIN oto_order_goods AS og ON g.goodsId = og.goodsId
LEFT JOIN oto_shops AS s ON s.shopId = g.shopId
$where
GROUP BY
	og.goodsId
	$having
ORDER BY
	$order
Eof;
            // $count = M()->query($csql);
            // $this->count = count($count);
    return M()->query($sql);
    //echo M()->getLastSql();die;
            //return M()->query($sql);
           // $this->info = $info;
        } //else {


//             //搜索店铺
//             if (! empty($key)) {
//                 $page = I('get.page');
//                 $sort = I('get.sorts');
//                 $sales = I('get.sales');
//                 $key = I('get.key');
//                 $limit = 10;
//                 $step = $page * $page;
//                 $order = "";
//                 $sale = "";
//                 if ($sales) {
//                     $sale = 'monthCount DESC , ';
//                 }
//                 switch ($sort) {
//                     // 智能
//                     case 'smart':
//                         $order = "$sale shopId DESC";
//                         break;
//                     // 配送费
//                     case 'freight':
//                         $order = "$sale deliveryStartMoney ASC";
//                         break;
//                     // 销量
//                     case 'volume':
//                         $order = "monthCount DESC";
//                         break;
//                     default:
//                         $order = "shopId DESC";
//                 }
//                 $shopWhere=" where s.shopName LIKE '%$key%'";
//                 //如果存在品牌
//                 if($brand){
//                     $shopWhere = " where  s.shopName LIKE '%$key%' and exists(select 1 from oto_goods where oto_goods.shopId=s.shopId and oto_goods.brandId=$brand)";
//                 }
//                 $shopWhere.="and s.shopStatus=1 and s.shopFlag=1";
//                 $shop_sql = <<<Eof
//             SELECT
// 	s.shopId,
// 	s.shopName,
// 	s.shopImg,
// 	s.serviceStartTime,
// 	s.serviceEndTime,
// 	s.deliveryStartMoney,
//     s.deliveryFreeMoney,
//                 s.avgeCostMoney,
// 	(
// 		SELECT
// 			count(oto_orders.orderId)
// 		FROM
// 			oto_order_goods
// 		JOIN oto_orders ON oto_order_goods.orderId = oto_orders.orderId
// 		WHERE
// 			(
// 				oto_orders.isPay = 1
// 				OR oto_orders.payType = 0
// 			)
// 		AND oto_orders.isClosed = 0
// 		AND oto_orders.isRefund = 0
// 		AND oto_orders.paytime-$mtime<2592000
// 		AND oto_orders.shopId = s.shopId
// 	) AS monthCount
// FROM
// 	oto_shops AS s
// LEFT JOIN oto_orders AS o ON o.shopId = s.shopId
// LEFT JOIN oto_order_goods AS og ON o.orderId = og.orderId
//  $shopWhere
// GROUP BY
// 	s.shopId
// ORDER BY
// 	$sale $order
// Eof;
//                 return M()->query($shop_sql);
//                 //$this->countShop = count($this->shopInfo);
//             }

//         }
        // 推荐一些品牌
        // $this->brand = M('brands')->where(array('brandFlag' => 1))
        //     ->order('brandId DESC')
        //     ->limit(12)
        //     ->select();
        // if( I('get.type') == 'shops'){
        //     $this->display('search-shops');
        // }

        // $this->display('search-goods');

    }
}